from PyPDF2 import PdfFileWriter, PdfFileReader
import os

def get_pdf_pn(flfp):
    pdf_reader = PdfFileReader(flfp)
    return pdf_reader.getNumPages()

def keep_page( str1,flfp):
    i_s=1
    i_e=1
    
    if str1.find(" ")>0:
        istr1 =  str1.split(" ")
        i_s= int(istr1[0])
        i_e = int(istr1[1])
    else:
        i_s=int(str1)
        i_e=int(str1)
    pdf_reader = PdfFileReader(flfp)
    pdf_writer = PdfFileWriter()
    i=0
    for page in range(pdf_reader.getNumPages()):
        i=i+1
        if i>= i_s and i<=i_e:            
            pdf_writer.addPage(pdf_reader.getPage(page))
    with open(flfp, 'wb') as out:
        pdf_writer.write(out)
if __name__ == "__main__":
    str1 = ""
    rootfd = input("请输入需要遍历pdf的文件夹")
    for root, dirs, files in os.walk(rootfd, topdown=False):
        for fl in files:
            if fl[-4:] == ".pdf" or fl[-4:] == ".PDF":
                print(fl)
                pgn =get_pdf_pn( os.path.join(root,fl))
                if pgn  > 1 :
                    str1 = "X"
                    str2 = "XX"
                    while str1 != str2 or str1.find(" ")==0 :
                        str1 = input( str(pgn) + "页" + fl + "您的选择数字保留页")
                        str2 = input( "再次输入您的选择来确认")
                        if str1 =="o o" or str2 == "o o":
                            os.startfile(os.path.join(root,fl))
                            str1 ="X"
                            str2 = "XX"
                    if str1 =="n n":
                        pass
                    else:
                        keep_page(str1, os.path.join(root,fl) )